package notify

import (
	"encoding/json"
	"enotify/pkg/notify/conf"
	"enotify/pkg/notify/provider/urora"
	"fmt"
)

func NewAppMsg(user []string,title,msg,url string) AppMsg {
	return AppMsg{
		User: user,
		Title: title,
		Msg: msg,
		Url: url,
	}
}

type AppMsg struct {
	User []string `json:"user"`
	Title string `json:"title"`
	Msg string `json:"msg"`
	Url string `json:"url"`
}

func (app AppMsg) encode() ([]byte,error) {
	data, err := json.Marshal(app)
	return data,err
}
func decodeApp(data []byte) (AppMsg,error) {
	var app AppMsg
	err := json.Unmarshal(data,&app)
	return app,err
}

func (s *Sender) SendApp(bizType string,msg AppMsg) error{

	reply := NewSendReply(0,"")
	data, err := msg.encode()

	if err != nil  {
		reply.Code = 10001
		reply.Msg = err.Error()
		return reply
	}
	task := Task{
		bizType: bizType,
		data:    data,
		sender:  s.appSender,
	}
	return s.send(task)
}
func SenderWithApp(c *conf.Config) option{
	return func(s *Sender) {
		s.appSender = NewAppSender(c)
	}
}
func NewAppSender(c *conf.Config) *AppSender {

	return &AppSender{
		c:   c,
	}
}
type AppSender struct {
	c *conf.Config
}
func (s *AppSender) Send(bizType string,jn []byte) (reply *SendReply){
	reply = NewSendReply(0,"")
	var err error
	appMsg,err := decodeApp(jn)
	if err != nil {
		reply.Code = 10001
		reply.Msg = err.Error()
	}
	var appConf *conf.AppConf
	var ok bool
	if appConf,ok = s.c.App[bizType]; ok {
	} else {
		reply.Code = 10001
		reply.Msg = fmt.Sprintf("bizType:%s err",bizType)
		return
	}
	if err != nil {
		reply.Code = 10002
		reply.Msg = err.Error()
	}

	switch bizType {
	case "jiguang":
		reply = s.urora(*appConf,appMsg.User,appMsg.Title,appMsg.Msg,appMsg.Url)
	default:
		fmt.Println("he he --------------")
	}
	return

}
func (s *AppSender) urora(conf conf.AppConf, user []string,title string,msg string,url string) *SendReply{
	uconf := urora.Config{
		AppKey: conf.AppId,
		Secret: conf.Secret,
	}
	pusher := urora.NewPushV3(&uconf,nil)

	options := urora.Options{
		ApnsProduction: false,
	}
	audience := urora.Audience{
		Alias: user,
	}
	ios := urora.IOS{
		Title: title,
		Body:    msg,
		Extras: urora.Extras{
			Type:   "openUrl",
			Url:    url,
		},
		ContentAvailable: false,
		Category: "system",
	}
	android := urora.Android{
		Alert:      msg,
		Title:      title,
		BuilderId: 1,
		Extras: urora.Extras{
			Type:   "openUrl",
			Url:    url,
		},
	}
	pusher.SetOption(options)
	pusher.SetAudience(audience)
	pusher.NotificationWithIOS(ios)
	pusher.NotificationWithAndroid(android)
	reply := NewSendReply(0,"")
	msgId,err := pusher.Send()
	fmt.Println(err)
	if err != nil {
		reply.Code = 10001
		reply.Msg = err.Error()
		return reply
	}
	reply.Reply = msgId
	return reply
}